//
// Created by user on 2022/3/22.
//

#include <vector>
using namespace std;
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};


void preOrder(TreeNode* node, int currLevel, vector<vector<int>>& res);
vector<vector<int>> levelOrderBottom(TreeNode* root) {
    if (!root) return {};

    vector<vector<int>> res;
    preOrder(root, 0, res);
    reverse(res.begin(), res.end());
    return res;
}

void preOrder(TreeNode* node, int currLevel, vector<vector<int>>& res) {
    if (!node) return;

    if (res.size() == currLevel) {
        vector<int> levelNodes = {node->val};
        res.push_back(levelNodes);
    } else {
        res[currLevel].push_back(node->val);
    }

    preOrder(node->left, currLevel + 1, res);
    preOrder(node->right, currLevel + 1,  res);
}